# @author: Samuel Taylor <samtaylor.uk@gmail.com>
# @package: winecellar
# @license: GNU GPLv3
#
# Copyright (C) 2010  Samuel Taylor <samtaylor.uk@gmail.com>
#----------------------------------------------------------------------
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#-----------------------------------------------------------------------

__author__ = 'Samuel Taylor <samtaylor.uk@gmail.com>'

import os
import shutil
from lxml import etree
import WineCellar.Config
from WineCellar.Bottle import Bottle
from WineCellar.Preferences import Preferences
from WineCellar.Logger import logger
class BottleManager:
    """
    This class create, deletes and manages wine bottles.
    """
    def create(self, bottleName):
        """
        creates a wine bottle and sets it up.
        """
        logger.info("Creating bottle: " + bottleName)
        if not self.exist(bottleName):
            logger.debug("Creating bottle folder: " + bottleName)
            if not os.path.exists(str(Config.__bottlepath__ + bottleName)):
                os.makedirs(str(Config.__bottlepath__ + bottleName))            
            else:
                logger.warn("Bottle folder already exixts: " + bottleName)
            
            bottleXML = etree.Element("bottle")
            etree.SubElement(bottleXML, "name").text = bottleName

            f = open(str(Config.__bottlepath__ + bottleName +'/bottle.xml'), 'w')
            logger.debug("Creating bottle config file: " + bottleName)
            f.write(etree.tostring(bottleXML, pretty_print=True, encoding='iso-8859-1'))
            f.close()

            logger.debug("Creating bottle Wine Prefix: " + bottleName)
            code = os.system( "WINEDEBUG=-all wineprefixcreate -q --prefix %s -w > /dev/null 2>&1" % str(Config.__bottlepath__ + bottleName) )
            logger.debug("Creating bottle Wine Prefix: " + bottleName+" Return code: "+str(code))
            
            self.NewBottle = Bottle(bottleName)
            self.NewBottle.setup()
            
            return True
        else:
            logger.error("Bottle already exixts: " + bottleName)
            return False
    
    def delete(self, bottleName):
        """
        Deletes a wine bottle and removes folder.
        """
        logger.info("Deleting bottle: " + bottleName)
        if os.path.exists(str(Config.__bottlepath__ + bottleName)):
            shutil.rmtree(str(Config.__bottlepath__ + bottleName))
            return True
        else:
            logger.error("Bottle doesn't exist: " + bottleName)
            return False

    def exist(self, bottleName):
        """
        Checks if a wine bottle exists.
        """
        if os.path.exists(str(Config.__bottlepath__ + bottleName)):
            if os.path.exists(str(Config.__bottlepath__ + bottleName + "/bottle.xml")):
                if os.path.exists(str(Config.__bottlepath__ + bottleName + "/drive_c")):
                    return True
                    
        return False
            
    def list(self):
        """
        Returns a list of all wine bottles.
        """
        bottleList = []
        if os.path.exists(str(Config.__bottlepath__)):
            for file in os.listdir(str(Config.__bottlepath__ )):
                dirfile = os.path.join(str(Config.__bottlepath__ ), file)
                if os.path.isdir(dirfile):
                    parser = etree.XMLParser(remove_blank_text=True)
                    tree = etree.parse(str(dirfile +'/bottle.xml'), parser)

                    bottleList.append(tree.find("name").text)     
            return bottleList
        else:
            return False

    def isInstalled(self, shortName):
        """
        Checks if application is installed in any bottle
        """
        if self.list() != False:
            for bottle in self.list():
                if Bottle(bottle).isInstalled(shortName):
                    return True

        return False

    def listNotApp(self, shortName):
        """
        Returns a list of bottle that don't have a app in
        """
        bottleList = []

        for bottle in self.list():
            if not Bottle(bottle).isInstalled(shortName):
                bottleList.append(bottle)

        return bottleList
